// pages/receive_info_personal/receive_info_personal.js
const util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    genderType: ["点击选择性别","男", "女"],
    genderTypeIndex: 0,
    personal_list : [],
    cWidth: 0,
    cHeight: 0
  },
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading()
    this.onLoad()
    setTimeout(() => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    }, 2000);
  },
  go_select: function(e){
    wx.navigateTo({
      url: '../receive_info_select/receive_info_select?type=1',
    })
  },
  genderChange: function(e){
    var index = e.currentTarget.dataset.index;
    var receive_info = util.getUserArr('help_receive_info')
    receive_info[index].personal_gender = e.detail.value
    this.setData({
      personal_list : receive_info
    });
    util.setUserdata('help_receive_info',receive_info)
  },
  choose_identity_card_front_files: function (e) {
      var that = this
      var index = e.currentTarget.dataset.index
      if(this.data.personal_list[index].identity_card_front_path) return;
      wx.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera'], 
          success: function (photo) {
            var image_size = 5 * 1024 * 1024
            if (photo.tempFiles[0].size > image_size) {
              wx.showToast({
                title: '上传图片不能超过5M',
                icon: 'none',
                duration: 2000
              })
              return false
            }

            wx.getImageInfo({
              src: photo.tempFilePaths[0],
              success: function (res) {
                console.log(res);
                //---------利用canvas压缩图片--------------
                var ratio = 2;
                var canvasWidth = res.width //图片原始长宽
                var canvasHeight = res.height
                while (canvasWidth > 1024 || canvasHeight > 1024) {// 保证宽高在400以内
                  canvasWidth = Math.trunc(res.width / ratio)
                  canvasHeight = Math.trunc(res.height / ratio)
                  ratio++;
                }
                that.setData({
                  cWidth: canvasWidth,
                  cHeight: canvasHeight
                })

                //----------绘制图形并取出图片路径--------------
                var ctx = wx.createCanvasContext('identity_card_front_files')
                ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)
                ctx.draw(false, setTimeout(function () {
                  wx.canvasToTempFilePath({
                    canvasId: 'identity_card_front_files',
                    destWidth: canvasWidth,
                    destHeight: canvasHeight,
                    success: function (result) {
                      console.log(result.tempFilePath)//最终图片路径

                      //上传图片
                      wx.showLoading({
                        title: '图片上传中',
                        icon: 'loading',
                        mask: true
                      })
                      wx.uploadFile({
                        url: util.reqUrl('V2/uploadIdentityFront'),
                        header: util.headers(),
                        formData: { 'identity_token': util.getUserdata('identity_token') },
                        filePath: result.tempFilePath,
                        name: 'identity_card_front_' + index,
                        success(res) {
                          wx.hideLoading()
                          var rtn = JSON.parse(res.data)
                          if (rtn.code < 0) {
                            wx.showToast({
                              title: rtn.err,
                              icon: 'none',
                              duration: 2000
                            })
                            return false
                          }
                          var receive_info = util.getUserArr('help_receive_info')
                          receive_info[index].identity_card_front_vc = rtn.verify_code

                          receive_info[index].identity_card_front_path = ['https://gongzheng.ma.cn/MYPublic/' + rtn.image_name]

                          if (rtn.personal_name) {
                            receive_info[index].personal_name = rtn.personal_name
                          }

                          // if (rtn.identity_address) {
                          //   receive_info[index].identity_address = rtn.identity_address
                          // }

                          if (rtn.identity_code) {
                            receive_info[index].identity_code = rtn.identity_code
                          }

                          if (rtn.personal_gender) {
                            receive_info[index].personal_gender = rtn.personal_gender
                          }

                          if (rtn.personal_birth_date) {
                            receive_info[index].personal_birth_date = rtn.personal_birth_date
                          }

                          that.setData({
                            personal_list: receive_info
                          })

                          util.setUserdata('help_receive_info', receive_info)
                        }
                      })

                    },
                    fail: function (res) {
                      console.log(res.errMsg)
                    }
                  })
                }, 500))
              }
            })
          }
      })
  },
  choose_identity_card_back_files: function (e) {
      var that = this
      var index = e.currentTarget.dataset.index
      if(this.data.personal_list[index].identity_card_back_path) return;
      wx.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera'], 
          success: function (photo) {
            var image_size = 5 * 1024 * 1024
            if (photo.tempFiles[0].size > image_size) {
              wx.showToast({
                title: '上传图片不能超过5M',
                icon: 'none',
                duration: 2000
              })
              return false
            }

            wx.getImageInfo({
              src: photo.tempFilePaths[0],
              success: function (res) {
                console.log(res);
                //---------利用canvas压缩图片--------------
                var ratio = 2;
                var canvasWidth = res.width //图片原始长宽
                var canvasHeight = res.height
                while (canvasWidth > 1024 || canvasHeight > 1024) {// 保证宽高在400以内
                  canvasWidth = Math.trunc(res.width / ratio)
                  canvasHeight = Math.trunc(res.height / ratio)
                  ratio++;
                }
                that.setData({
                  cWidth: canvasWidth,
                  cHeight: canvasHeight
                })

                //----------绘制图形并取出图片路径--------------
                var ctx = wx.createCanvasContext('identity_card_back_files')
                ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)
                ctx.draw(false, setTimeout(function () {
                  wx.canvasToTempFilePath({
                    canvasId: 'identity_card_back_files',
                    destWidth: canvasWidth,
                    destHeight: canvasHeight,
                    success: function (result) {
                      console.log(result.tempFilePath)//最终图片路径

                      //上传图片
                      wx.showLoading({
                        title: '图片上传中',
                        icon: 'loading',
                        mask: true
                      })
                      wx.uploadFile({
                        url: util.reqUrl('V2/uploadIdentityBack'),
                        header: util.headers(),
                        formData: { 'identity_token': util.getUserdata('identity_token') },
                        filePath: result.tempFilePath,
                        name: 'identity_card_back_' + index,
                        success(res) {
                          wx.hideLoading()
                          var rtn = JSON.parse(res.data)
                          if (rtn.code < 0) {
                            wx.showToast({
                              title: rtn.err,
                              icon: 'none',
                              duration: 2000
                            })
                            return false
                          }
                          var receive_info = util.getUserArr('help_receive_info')
                          receive_info[index].identity_card_back_vc = rtn.verify_code

                          receive_info[index].identity_card_back_path = ['https://gongzheng.ma.cn/MYPublic/' + rtn.image_name]

                          that.setData({
                            personal_list: receive_info
                          })

                          util.setUserdata('help_receive_info', receive_info)
                        }
                      })

                    },
                    fail: function (res) {
                      console.log(res.errMsg)
                    }
                  })
                }, 500))
              }
            })
          }
      })
  },
  save: function (e) {
    var that = this
    var index = e.currentTarget.dataset.index
    var pageData = that.data.personal_list
    var receive_remarkp = ''

    // for (var i = 0; i < pageData.length; i++) {
      if (pageData[index].receive_type == 1) {

        if (!pageData[index].identity_card_front_path) {
          wx.showToast({
            title: '请上传身份证正面照片',
            icon: 'none',
            duration: 2000
          })
          return false
        }

        if (!pageData[index].identity_card_back_path) {
          wx.showToast({
            title: '请上传身份证背面照片',
            icon: 'none',
            duration: 2000
          })
          return false
        }

        if (pageData[index].personal_name == '') {
          wx.showToast({
            title: '请输入姓名',
            icon: 'none',
            duration: 2000
          })
          return false
        }
        receive_remarkp += '受让人:' + pageData[index].personal_name + ';'

        if (pageData[index].identity_code == '') {
          wx.showToast({
            title: '请输入身份证',
            icon: 'none',
            duration: 2000
          })
          return false
        }

        receive_remarkp += '身份证:' + pageData[index].identity_code + ';'

        if (pageData[index].personal_gender == 0) {
          wx.showToast({
            title: '请选择性别',
            icon: 'none',
            duration: 2000
          })
          return false
        }

        if (pageData[index].personal_birth_date == '') {
          wx.showToast({
            title: '请选择出生日期',
            icon: 'none',
            duration: 2000
          })
          return false
        }

        if (pageData[index].identity_address == '') {
          wx.showToast({
            title: '请填写身份证地址',
            icon: 'none',
            duration: 2000
          })
          return false
        }

        // receive_remarkp += '地址:' + pageData[index].identity_address + ';'

        // if (!pageData[index].personal_address) {
        //   wx.showToast({
        //     title: '请填写联系地址',
        //     icon: 'none',
        //     duration: 2000
        //   })
        //   return false
        // }

        // if (!pageData[index].personal_phone) {
        //   wx.showToast({
        //     title: '请填写手机',
        //     icon: 'none',
        //     duration: 2000
        //   })
        //   return false
        // }

        pageData[index].isShow = true
        pageData[index].receive_remarkp = receive_remarkp
      }
    // }
    
    var receive_info = util.getUserArr('help_receive_info')
    receive_info[index].identity_address = pageData[index].identity_address
    receive_info[index].identity_card_back_path = pageData[index].identity_card_back_path
    receive_info[index].identity_card_back_vc = pageData[index].identity_card_back_vc
    receive_info[index].identity_card_front_path = pageData[index].identity_card_front_path
    receive_info[index].identity_card_front_vc = pageData[index].identity_card_front_vc
    receive_info[index].identity_code = pageData[index].identity_code
    receive_info[index].personal_address = pageData[index].personal_address
    receive_info[index].personal_birth_date = pageData[index].personal_birth_date
    receive_info[index].personal_gender = pageData[index].personal_gender
    receive_info[index].personal_name = pageData[index].personal_name
    receive_info[index].personal_phone = pageData[index].personal_phone
    receive_info[index].receive_type = 1
    receive_info[index].isShow = pageData[index].isShow

    that.setData({
      personal_list: pageData
    })

    console.log(receive_info);
    wx.showToast({
      title: '保存成功',
      icon: 'none',
      duration: 2000
    })
    wx.reLaunch({
      url: '../help_get_notarization/help_get_notarization',
    })
    return false

    wx.showModal({
      title: '提示',
      content: '是否确认保存',
      cancelText: "返回",
      confirmText: "继续添加",
      success: function (sm) {
        util.setUserdata('help_receive_info', receive_info)
        if (sm.cancel) {
          wx.navigateTo({
            url: '../help_receive_info/help_receive_info',
          })
        }
      }
    })
  },
  add: function () {
    var receive_info = util.getUserArr('help_receive_info')
    for (var i = 0; i < receive_info.length; i++) {
      if (receive_info[i].receive_type == 1) {
        var receive_remarkp = ''
        var num = 0
        if (receive_info[i].identity_card_front_path) {
          console.log('kk' + 1)
          num += 1
        } else {
          wx.showToast({
            title: '请上传身份证正面照片',
            icon: 'none',
            duration: 2000
          })
          return false
        }
        if (receive_info[i].identity_card_back_path) {
          console.log('kk' + 2)
          num += 1
        } else {
          wx.showToast({
            title: '请上传身份证背面照片',
            icon: 'none',
            duration: 2000
          })
          return false
        }
        if (receive_info[i].personal_name) {
          console.log('kk' + 3)
          receive_remarkp += '受让人:' + receive_info[i].personal_name + ';'
          num += 1
        } else {
          wx.showToast({
            title: '请上传姓名',
            icon: 'none',
            duration: 2000
          })
          return false
        }
        if (receive_info[i].identity_code) {
          console.log('kk' + 7)
          receive_remarkp += '身份证号:' + receive_info[i].identity_code + ';'
          num += 1
        } else {
          wx.showToast({
            title: '请填写身份证号码',
            icon: 'none',
            duration: 2000
          })
          return false
        }
        if (receive_info[i].personal_gender) {
          console.log('kk' + 4)
          num += 1
        } else {
          wx.showToast({
            title: '请选择性别',
            icon: 'none',
            duration: 2000
          })
          return false
        }
        if (receive_info[i].personal_birth_date) {
          console.log('kk' + 5)
          num += 1
        } else {
          wx.showToast({
            title: '请选择出生日期',
            icon: 'none',
            duration: 2000
          })
          return false
        }
        
        // if (receive_info[i].identity_address) {
        //   console.log('kk' + 6)
        //   receive_remarkp += '地址:' + receive_info[i].identity_address + ';'
        //   num += 1
        // } else {
        //   wx.showToast({
        //     title: '请填写地址',
        //     icon: 'none',
        //     duration: 2000
        //   })
        //   return false
        // }

        // if (receive_info[i].personal_address) {
        //   console.log('kk' + 6)
        //   num += 1
        // } else {
        //   wx.showToast({
        //     title: '请填写联系地址',
        //     icon: 'none',
        //     duration: 2000
        //   })
        //   return false
        // }

        // if (receive_info[i].personal_phone) {
        //   console.log('kk' + 6)
        //   num += 1
        // } else {
        //   wx.showToast({
        //     title: '请填写手机',
        //     icon: 'none',
        //     duration: 2000
        //   })
        //   return false
        // }



        console.log(num)
        //后面改7
        if (num >= 9) {
          console.log('ok')
          receive_info[i].isShow = true
          receive_info[i].receive_remarkp = receive_remarkp
        }
      }
    }

    receive_info.push({ 'receive_type': 1, 'ot': false, isShow: false, receive_remarkp: ''})
    this.setData({
      personal_list: receive_info
    })
    console.log(receive_info)
    util.setUserdata('help_receive_info',receive_info)

  },
  change_isShow: function (e) {
    var that = this
    var index = e.currentTarget.dataset.index
    var pageData = that.data.personal_list
    var receive_remarkp = ''
    var receive_info = util.getUserArr('help_receive_info')

    console.log(receive_info);
    receive_info[index].isShow = !receive_info[index].isShow
    pageData[index].personal_name ? receive_remarkp += '受让人:' + pageData[index].personal_name + ';' : ''
    pageData[index].identity_code ? receive_remarkp += '身份证:' + pageData[index].identity_code + ';' : ''
    // pageData[index].identity_address ? receive_remarkp += '地址:' + pageData[index].identity_address + ';' : ''

    receive_info[index].receive_remarkp = receive_remarkp
    that.setData({
      personal_list: receive_info
    })
    util.setUserdata('help_receive_info', receive_info)
  },
  del: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index
    var receive_info = util.getUserArr('help_receive_info')
    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          if (receive_info[index].transfer_type != 1) {
            console.log(receive_info[index])
          }
          receive_info.splice(index, 1)
          that.setData({
            personal_list: receive_info
          })
          util.setUserdata('help_receive_info', receive_info)
        }
      }
    })
    
  },
  preview_identity_card_front_files: function(e){
    var index = e.currentTarget.dataset.index
    if(this.data.personal_list[index].identity_card_front_path){
      wx.previewImage({
        urls: this.data.personal_list[index].identity_card_front_path
      })
    }
  },
  preview_identity_card_back_files: function(e){
    var index = e.currentTarget.dataset.index;
    if(this.data.personal_list[index].identity_card_back_path){
      wx.previewImage({
        urls: this.data.personal_list[index].identity_card_back_path
      })
    }
  },
  touchStart: function(e){
    this.touchTimeStamp = e.timeStamp
  },
  touchEnd: function (e) {
    var diff = e.timeStamp - this.touchTimeStamp
    var tag = e.currentTarget.dataset.tag
    if (tag == 'identity_card_front_block'){
      diff >= 500 ? this.delete_identity_card_front_files(e) : this.preview_identity_card_front_files(e)
    } 
    if (tag == 'identity_card_back_block') {
      diff >= 500 ? this.delete_identity_card_back_files(e) : this.preview_identity_card_back_files(e)
    } 
  },
  delete_identity_card_front_files: function(e){
    var index = e.currentTarget.dataset.index
    var that = this
    if(this.data.personal_list[index].identity_card_front_path){
      wx.showModal({
        title: '删除图片',
        content: '是否确认要删除该图片?',
        confirmText: "确认",
        cancelText: "取消",
        success: function (res) {
          if (res.confirm) {
            var receive_info = util.getUserArr('help_receive_info')
            receive_info[index].identity_card_front_path = '';
            receive_info[index].identity_card_front_vc = '';
            util.setUserdata('help_receive_info',receive_info)
            that.reload()
          } 
        }
      })
    }
  },
  delete_identity_card_back_files: function(e){
    var index = e.currentTarget.dataset.index
    var that = this
    if(this.data.personal_list[index].identity_card_back_path){
      wx.showModal({
        title: '删除图片',
        content: '是否确认要删除该图片?',
        confirmText: "确认",
        cancelText: "取消",
        success: function (res) {
          if (res.confirm) {
            var receive_info = util.getUserArr('help_receive_info')
            receive_info[index].identity_card_back_path = '';
            receive_info[index].identity_card_back_vc = '';
            util.setUserdata('help_receive_info',receive_info)
            that.reload()
          } 
        }
      })
    }
  },
  personal_name_input: function(e){
    var index = e.currentTarget.dataset.index;
    var receive_info = util.getUserArr('help_receive_info')
    receive_info[index].personal_name = e.detail.value
    this.setData({
      personal_list : receive_info
    });
    util.setUserdata('help_receive_info',receive_info);
  },
  identity_code_input: function(e){
    var index = e.currentTarget.dataset.index;
    var receive_info = util.getUserArr('help_receive_info')
    receive_info[index].identity_code = e.detail.value
    this.setData({
      personal_list : receive_info
    });
    util.setUserdata('help_receive_info',receive_info);
  },
  personal_gender_input: function(e){
    var index = e.currentTarget.dataset.index;
    var receive_info = util.getUserArr('receive_info')
    receive_info[index].personal_gender = e.detail.value
    this.setData({
      personal_list : receive_info
    });
    util.setUserdata('receive_info',receive_info);
  },
  personal_birth_date_input: function(e){
    var index = e.currentTarget.dataset.index;
    var receive_info = util.getUserArr('help_receive_info')
    receive_info[index].personal_birth_date = e.detail.value
    this.setData({
      personal_list : receive_info
    });
    util.setUserdata('help_receive_info',receive_info);
  },
  identity_address_input: function(e){
    var index = e.currentTarget.dataset.index;
    var receive_info = util.getUserArr('help_receive_info')
    receive_info[index].identity_address = e.detail.value
    this.setData({
      personal_list : receive_info
    });
    util.setUserdata('help_receive_info',receive_info);
  },
  personal_address_input: function(e){
    var index = e.currentTarget.dataset.index;
    var receive_info = util.getUserArr('help_receive_info')
    receive_info[index].personal_address = e.detail.value
    this.setData({
      personal_list : receive_info
    });
    util.setUserdata('help_receive_info',receive_info);
  },
  personal_phone_input: function(e){
    var index = e.currentTarget.dataset.index;
    var receive_info = util.getUserArr('help_receive_info')
    receive_info[index].personal_phone = e.detail.value
    this.setData({
      personal_list : receive_info
    });
    util.setUserdata('help_receive_info',receive_info);
  },
  clear_input: function(e){
    var that = this;
    var index = e.currentTarget.dataset.index
    var receive_info = util.getUserArr('help_receive_info')
    var pageList = that.data.personal_list

    wx.showModal({
      title: '提示',
      content: '确定要清空吗？',
      success: function (sm) {
        if (sm.confirm) {
          for (var i = 0; i < pageList.length; i++) {
            if (i == index && pageList[i].receive_type == 1) {
              pageList[i].identity_address = '';
              pageList[i].identity_card_back_path = '';
              pageList[i].identity_card_back_vc = '';
              pageList[i].identity_card_front_path = '';
              pageList[i].identity_card_front_vc = '';
              pageList[i].identity_code = '';
              pageList[i].personal_address = '';
              pageList[i].personal_birth_date = '';
              pageList[i].personal_gender = '';
              pageList[i].personal_name = '';
              pageList[i].personal_phone = '';
              pageList[i].receive_type = 1;
              pageList[i].receive_remarkp = '';
            }
          }
          that.setData({
            personal_list: pageList 
          });

          for (var i = 0; i < receive_info.length; i++) {
            if (i == index && receive_info[i].receive_type == 1) {
              receive_info[i].identity_address = '';
              receive_info[i].identity_address = '';
              receive_info[i].identity_card_back_path = '';
              receive_info[i].identity_card_back_vc = '';
              receive_info[i].identity_card_front_path = '';
              receive_info[i].identity_card_front_vc = '';
              receive_info[i].identity_code = '';
              receive_info[i].personal_address = '';
              receive_info[i].personal_birth_date = '';
              receive_info[i].personal_gender = '';
              receive_info[i].personal_name = '';
              receive_info[i].personal_phone = '';
              receive_info[i].receive_type = 1;
              receive_info[i].receive_remarkp = '';
            }
          }

          util.setUserdata('help_receive_info', receive_info)
        }
      }
    })
  },
  reload: function(){
    var receive_info = util.getUserArr('help_receive_info')
    for (var i = 0; i < receive_info.length; i++) {
      if (receive_info[i].receive_type == 1) {
        var receive_remarkp = ''
        var num = 0
        if (receive_info[i].identity_card_front_path) {
          num += 1
        }
        if (receive_info[i].identity_card_back_path) {
          num += 1
        }
        if (receive_info[i].personal_name) {
          receive_remarkp += '受让人:' + receive_info[i].personal_name + ';'
          num += 1
        }
        if (receive_info[i].identity_code) {
          receive_remarkp += '身份证号:' + receive_info[i].identity_code + ';'
          num += 1
        }
        if (receive_info[i].personal_gender) {
          num += 1
        }
        if (receive_info[i].personal_birth_date) {
          num += 1
        }
        if (receive_info[i].identity_address) {
          // receive_remarkp += '地址:' + receive_info[i].identity_address + ';'
          num += 1
        }

        if (receive_info[i].personal_address) {
          num += 1
        }
        if (receive_info[i].personal_phone) {
          num += 1
        }


        console.log(num)
        //后面改9
        if (num >= 9) {
          console.log('ok')
          receive_info[i].isShow = true

          receive_info[i].receive_remarkp = receive_remarkp
        }
      }

    }
    this.setData({
      personal_list : receive_info
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.reload()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.reload()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  touchTimeStamp: 0
})